package com.qfedu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qfedu.config.MySecurityConfig;
import com.qfedu.mapper.UserMapper;
import com.qfedu.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LiJH
 * @date 2023-02-03
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements MySecurityConfig, UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //GrantedAuthority 权限类，用来描述用户的角色和权限
        List<GrantedAuthority> list = new ArrayList<>();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",username);
        User user = this.baseMapper.selectOne(queryWrapper);
        if (user != null) {
            list.add(new SimpleGrantedAuthority("ROLE_USER"));
            list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            return new User(username, user.getPassword(), list);
        }
        return null;
    }
}